Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
React: FileReader onloadend doesn't recognize "this" if defined in a component method

I define a method in a React class component as follows

onSaveAudio = (e) => {
    e.preventDefault();
    const { audioBlob } = this.state;

    let reader = new FileReader();

    reader.onloadend = function () {
        const base64 = reader.result;
        const bstr = base64.split(',')[1];
        console.log(bstr);
        console.log('this.props', this.props);
        this.props.onSaveAudio(bstr);
    }

    reader.readAsDataURL(audioBlob);
    
    }

At the console.log('this.props', this.props) line, it's printing "undefined"; at the this.props.onSaveAudio line, an error is thrown:

Uncaught TypeError: Cannot read property 'onSaveAudio' of undefined at FileReader.reader.onloadend (recorder.js:300)

My understanding is that "onloadend" is triggered after the "reader" finishes reading "audioBlob". I need to call the this.props.onSaveAudio in the "onloadend" function, because if I call it outside of "onloadend", I can't time the call to after the reading finishes and "reader.result" is ready, and "bstr" would resolve to undefined with the wrong timing; but if I call the this.props.onSaveAudio within "onloadend", then "this" is not recognized. Seems to be a dilemma.

My guess is I need a solution to either bind "this" within "onloadend", or be able to somehow time a this.props.onSaveAudio call outside of the "onloadend" function, after the "onloadend" function finishes execution.

Any advice?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

One way I found is to use an arrow function when defining "reader.onloadend".

    reader.onloadend = () => {
        const base64 = reader.result;
        const bstr = base64.split(',')[1];
        console.log(bstr);
        console.log('this.props', this.props);
        this.props.onSaveAudio(bstr);
    }

this.props will be defined in this case

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!